<?php
declare (strict_types=1);

namespace app\api\controller;
use app\model\UserModel;


use think\facade\Request;
use think\facade\Validate;

class Login
{
public function logincheck()
    {
        $appid='wx9e1dd4a45d5b9478';
        $AppSecret='049dcb4eb110ebbf4ab049d8a251e44b';
        
        $code=Request::param('code');
        $userName=Request::param('user_name');
        $userImg=Request::param('user_img');
        
       $url="https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $AppSecret . "&js_code=" . $code . "&grant_type=authorization_code";

        //   $data = [
        //     'status' => 0,
        //     'message' => '登录成功',
        //     'data' => [
        //         "url"=>$url,
        //         "code"=>$code,
        //         "user_name"=>$userName,
        //         "user_img"=>$userImg,
        //         ]
        // ];
        // return json($data); 
        
        $res  = $this-> curl_post($url);
        var_dump($res);
        
        if($res){
            $res         = json_decode($res, true);
            $openid      = $res['openid'];
            $session_key = $res['session_key'];

        }
        $session3rd           = UserModel::encode($openid);
        $value['openid']      = $openid;
        $value['session_key'] = $session_key;
      
        $user=UserModel::where("open_id","=",$openid)->find();
        //如果该微信用户不存在，将其添加到后台数据库
        if(!$user){
            
            $user['user_name']=$userName;
            $user['user_img']=$userImg;
            $user['open_id']=$openid;
            $user['add_time']=$user['update_time']=time();
            
            $result=UserModel::create($user);
        }
        $data['session3rd'] = $session3rd;
        $data['msg']        = "登录成功";
        $data['code']       = 200;
        return json($data);
        
    }
    
    function curl_post($url, $param = array())
        {
    if (!is_array($param)) {
        throw new Exception("参数必须为array");
    }
    //转成json格式
    //$param=urldecode(json_encode($param));
    //var_dump($param);
    //$headerInfo=array('Content-Type:application/json');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //跟踪301
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_POST, 1); //设置为POST方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param); //设置参数
    //curl_setopt ($ch, CURLOPT_HTTPHEADER, $headerInfo);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
        
        
    }


}
